package com.datastructure.test.minsubarray;

public class MinSubArray {

    public static void main(String[] args) {

    }

    public int min = Integer.MAX_VALUE;
    public int minSubarray (int[] nums, int target) {
        // write code here
        for (int num : nums) {
            if (num >= target) {
                return 1;
            }
        }
        for (int i = 0; i < nums.length; i++) {
            computeMinSubArray(i,nums,target);
        }
        if(min==Integer.MAX_VALUE){
            return 0;
        } else {
            return min;
        }
    }

    private void computeMinSubArray(int start, int[] nums, int target) {
        if(min==1){
            return;
        }
        int sum =0;
        for(int i = start;i< nums.length;i++){
            sum+=nums[i];
            if(sum>=target){
                min=Math.min(min,i-start+1);
            }
        }
    }

    public int minSubarray1 (int[] nums, int target) {
        // write code here
        int left = 0;
        int right = 0;
        int n = nums.length;
        int sum = 0;
        int res = Integer.MAX_VALUE;
        while (right < n) {
            sum += nums[right++];
            while (left < right && sum >= target) {
                res = Math.min(res, right - left);
                sum -= nums[left++];
            }
        }
        return res;
    }
}
